/*

 * Copyright (c) 2017-2018, FastDev 刘强 (fastdev@163.com).

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *      http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

package of.hotswapinject.plugin.imp;

import of.hotswapinject.core.common.Util;
import org.apache.commons.cli.Option;
import of.hotswapinject.core.plugin.IMethodEnterPlugin;
import of.hotswapinject.core.plugin.IMethodExitPlugin;
import of.hotswapinject.core.plugin.IMethodFilter;
import of.hotswapinject.core.plugin.MethodMeta;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MethodResultCache extends MethodFilterBase {
    private static Map<String, Object> cacheMap = new ConcurrentHashMap<String, Object>();
    private static Object NULLOBJECT = new Object();
    private static Option resultCache;

    static {
        resultCache = new Option("c", "resultCache", false, "cache method return value");
        resultCache.setRequired(false);
    }

    @Override
    protected boolean canHandle(String key, MethodMeta adviceAdapter) {
        return adviceAdapter.hasReturnValue;
    }

    @Override
    protected boolean hookExitOnException(MethodMeta adviceAdapter) {
        return false;
    }


    @Override
    public IMethodEnterPlugin.ReturnParam onEnter(String key, Object[] params) {
        String[] concatParams = new String[] { key, Util.toJSONString(params) };
        String cacheKey = Util.concat(concatParams);
        Object cacheValue = cacheMap.get(cacheKey);
        if(cacheValue == null) {
            return IMethodEnterPlugin.ReturnParam.none();
        }

        if(cacheValue == NULLOBJECT) {
            cacheValue = null;
        }
        Util.trace("cached:" + key + "," + cacheValue);
        return IMethodEnterPlugin.ReturnParam.returnResult(cacheValue);
    }

    @Override
    public IMethodExitPlugin.ReturnParam onExit(String key, Object[] params, Object result) {
        String[] concatParams = new String[] { key, Util.toJSONString(params) };
        String cacheKey = Util.concat(concatParams);
        if(result == null) {
            result = NULLOBJECT;
        }
        cacheMap.put(cacheKey, result);
        return IMethodExitPlugin.ReturnParam.none();
    }


    @Override
    public Option getOption() {
        return resultCache;
    }
}
